package com.qhhc.controller;

import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/tts")
public class TtsController {

    private static final String TTS_SERVICE_URL = "http://127.0.0.1:9233/tts";
    private final RestTemplate restTemplate = new RestTemplate();

    @PostMapping
    public ResponseEntity<byte[]> textToSpeech(
            @RequestParam("text") String text,
            @RequestParam("role") String role) {
        try {
            // 构建multipart/form-data请求体
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("text", text);
            body.add("role", role);

            // 设置multipart头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            // 发送请求
            ResponseEntity<byte[]> response = restTemplate.exchange(
                    TTS_SERVICE_URL,
                    HttpMethod.POST,
                    requestEntity,
                    byte[].class
            );

            // 返回音频响应（保持原样）
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType("audio/wav"))
                    .header(HttpHeaders.CONTENT_DISPOSITION, " filename=tts.wav")
                    .body(response.getBody());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
} 